﻿using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using QuestionnaireInvestigation.Data.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace QuestionnaireInvestigation.Authorization
{
    public class CustomOAuthProvider : OAuthAuthorizationServerProvider
    {
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var email = context.UserName;
            var password = context.Password;
            string nickname;
            if (!CheckCredential(email, password, out nickname))
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                context.Rejected();
                return Task.FromResult<object>(null);
            }
            var ticket = new Microsoft.Owin.Security.AuthenticationTicket(SetClaimsIdentity(context, email, nickname), new AuthenticationProperties());
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context, string email, string nickname)
        {
            var identity = new ClaimsIdentity("JWT");
            identity.AddClaim(new Claim("email", email));
            identity.AddClaim(new Claim("nickname", nickname));
            return identity;
        }

        private static bool CheckCredential(string email, string password, out string nickname)
        {
            var success = false;            // 用户名和密码验证
            try
            {
                AdminService service = new AdminService();
                var nickName = service.AdminLogin(email, password);
                if (nickName != null)
                {
                    nickname = nickName;
                    success = true;
                }
                else
                {
                    nickname = "";
                    success = false;
                }
            }
            catch
             {
                nickname = "";
                success = false;
            }
            return success;
        }


    }
}